import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class AddSimSales extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
	{
		doPost(request,response);
	}//doGet

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
    {
		RequestDispatcher dispatcher = null;
		try
		{
			String cardtype = request.getParameter("cardType");
			int count = Integer.parseInt(request.getParameter("count"));
			String outlet = request.getParameter("outid");
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airtel","root","root");
			Statement stmt = con.createStatement();
			Timestamp ts = null;
			System.out.println("card Type :: "+cardtype);
			ResultSet rs=stmt.executeQuery("select count from simstock where cardType='"+cardtype+"'");
			if(rs.next())
			{
				int id = 0;
				int cardid = Integer.parseInt(cardtype);
				int outid = Integer.parseInt(outlet);
				int stock = Integer.parseInt(rs.getString(1));
				stock -= count;

				stmt.executeUpdate("update simstock set count='"+stock+"' where cardType='"+cardtype+"'");	
				rs=stmt.executeQuery("select max(id) from simsale");
				if(rs.next())
				{
					id = Integer.parseInt(rs.getString(1));
				}
				id++;
		
				ts = new Timestamp( (new java.util.Date()).getTime() );
				stmt.executeUpdate("insert into simsale values('"+id+"','"+ts+"','"+count+"','"+outid+"','"+cardid+"')");
				request.setAttribute("msg", new String("Stock Updated"));    
			}
			else
			{
				request.setAttribute("msg", new String("Sorry Stock not available"));    
			}
			Collection vector = new Vector();
			rs = stmt.executeQuery("select id,name from outletdetails");
			while(rs.next())
			{
				vector.add(rs.getString(1));
				vector.add(rs.getString(2));
			}   
			request.setAttribute("outletnames",vector);
			dispatcher = request.getRequestDispatcher("/jsp/SimSales.jsp");
			dispatcher.forward(request,response);
		}//try
		catch(Exception e)
		{
            e.printStackTrace();
		}//catch
	}//doPost
}//class